package com.learning.platform.controller;

import com.learning.platform.dto.ApiResponse;
import com.learning.platform.dto.LearningStatsResponse;
import com.learning.platform.entity.LearningSession;
import com.learning.platform.enums.SessionType;
import com.learning.platform.service.LearningAnalyticsService;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Optional;

/**
 * 学习分析控制器
 */
@RestController
@RequestMapping("/api/v1/learning-analytics")
@PreAuthorize("hasRole('STUDENT') or hasRole('TEACHER') or hasRole('ADMIN')")
public class LearningAnalyticsController {
    
    private final LearningAnalyticsService analyticsService;
    
    public LearningAnalyticsController(LearningAnalyticsService analyticsService) {
        this.analyticsService = analyticsService;
    }
    
    /**
     * 获取学习统计数据
     */
    @GetMapping("/stats")
    public ResponseEntity<ApiResponse<LearningStatsResponse>> getLearningStats(
            Authentication authentication,
            @RequestParam(defaultValue = "30") int days) {
        
        if (authentication == null || authentication.getPrincipal() == null) {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "用户未认证")
            );
        }
        
        Object principal = authentication.getPrincipal();
        Long userId;
        
        if (principal instanceof com.learning.platform.security.UserPrincipal) {
            userId = ((com.learning.platform.security.UserPrincipal) principal).getUserId();
        } else {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "认证信息格式错误")
            );
        }
        
        LearningStatsResponse stats = analyticsService.getUserLearningStats(userId, days);
        return ResponseEntity.ok(ApiResponse.success(stats));
    }
    
    /**
     * 开始学习会话
     */
    @PostMapping("/sessions/start")
    public ResponseEntity<ApiResponse<LearningSession>> startLearningSession(
            Authentication authentication,
            @RequestParam Long courseId,
            @RequestParam(required = false) Long lessonId,
            @RequestParam(defaultValue = "VIDEO") SessionType sessionType) {
        
        if (authentication == null || authentication.getPrincipal() == null) {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "用户未认证")
            );
        }
        
        Object principal = authentication.getPrincipal();
        Long userId;
        
        if (principal instanceof com.learning.platform.security.UserPrincipal) {
            userId = ((com.learning.platform.security.UserPrincipal) principal).getUserId();
        } else {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "认证信息格式错误")
            );
        }
        
        LearningSession session = analyticsService.startLearningSession(userId, courseId, lessonId, sessionType);
        return ResponseEntity.ok(ApiResponse.success(session, "学习会话已开始"));
    }
    
    /**
     * 结束学习会话
     */
    @PutMapping("/sessions/{sessionId}/end")
    public ResponseEntity<ApiResponse<Void>> endLearningSession(
            @PathVariable Long sessionId,
            @RequestParam(required = false) BigDecimal progressPercentage) {
        
        analyticsService.endLearningSession(sessionId, progressPercentage);
        
        return ResponseEntity.ok(ApiResponse.success(null, "学习会话已结束"));
    }
    
    /**
     * 更新学习进度
     */
    @PutMapping("/sessions/{sessionId}/progress")
    public ResponseEntity<ApiResponse<Void>> updateLearningProgress(
            @PathVariable Long sessionId,
            @RequestParam BigDecimal progressPercentage) {
        
        analyticsService.updateLearningProgress(sessionId, progressPercentage);
        
        return ResponseEntity.ok(ApiResponse.success(null, "学习进度已更新"));
    }
    
    /**
     * 获取当前活跃的学习会话
     */
    @GetMapping("/sessions/active")
    public ResponseEntity<ApiResponse<LearningSession>> getActiveSession(
            Authentication authentication) {
        
        if (authentication == null || authentication.getPrincipal() == null) {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "用户未认证")
            );
        }
        
        Object principal = authentication.getPrincipal();
        Long userId;
        
        if (principal instanceof com.learning.platform.security.UserPrincipal) {
            userId = ((com.learning.platform.security.UserPrincipal) principal).getUserId();
        } else {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "认证信息格式错误")
            );
        }
        
        Optional<LearningSession> activeSession = analyticsService.getActiveSession(userId);
        
        if (activeSession.isPresent()) {
            return ResponseEntity.ok(ApiResponse.success(activeSession.get()));
        } else {
            return ResponseEntity.ok(ApiResponse.success(null, "没有活跃的学习会话"));
        }
    }
}
